package common.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtil
{

	public static boolean renameFile(String sourcePath, String targetPath)
	{
		File targetFile = new File(targetPath);

		if (targetFile.exists())
		{
			boolean result = targetFile.delete();
			if (!result)
				return false;
		}

		return new File(sourcePath).renameTo(targetFile);
	}

	public static List<String> fileToStringList(String path) throws IOException
	{
		return fileToStringList(path, false);
	}

	static public List<String> fileToStringList(String path, boolean ignoreEmptyRows) throws IOException
	{
		List<String> result = new ArrayList<String>();
		String row;

		BufferedReader reader = new BufferedReader(new FileReader(path));
		IOException error = null;

		try
		{
			while ((row = reader.readLine()) != null)
			{
				if (!ignoreEmptyRows || row.trim().length() > 0)
					result.add(row);
			}
		}
		catch (IOException e)
		{
			error = e;
		}
		finally
		{
			reader.close();
		}

		if (error != null)
			throw error;

		return result;
	}

	static public void StringListToFile(String path, List<String> rows) throws Exception
	{
		BufferedWriter writer = new BufferedWriter(new FileWriter(path));

		IOException error = null;

		try
		{
			for (String line : rows)
			{
				writer.write(line);
				writer.newLine();
			}
		}
		catch (IOException e)
		{
			error = e;
		}
		finally
		{
			writer.close();
		}

		if (error != null)
			throw error;
	}
}
